#include "Scene.h"
#include <sstream>

Scene::Scene (Ptr< TerrainModel > pTerrainModel,
              Ptr< myglStringControl > pStringPainter,
              Ptr< list< Ptr< Object > > > pObjects,
              Ptr< vector< Model > > pModels,
              Ptr< BattleStatus > pStatus,
              const SceneCoordSpaceInfo& coordSpaceInfo)
              : _coordSpaceInfo (coordSpaceInfo)
{
  _pStringPainter = pStringPainter;
  _pStatus = pStatus;
  _pTerrainModel = pTerrainModel;
  _pObjects = pObjects;
  _pModels = pModels;
  _width = _pTerrainModel->width ();
  _height = _pTerrainModel->height ();
  _altitude = _pTerrainModel->altitude ();
}



void Scene::draw ()
{
  glPushMatrix ();

  _coordSpaceInfo.transform ();

  // Set sun's position

  float r = _width / 2.0f;
  float centerX = r;
  float centerZ = 0.0f;

   GLfloat lightColor0[] = {1.0f, 0.7f, 0.4f, 1.0f};
    GLfloat lightPos0[] = {
      centerX + r * cos (_pStatus->sun_degree () * 3.14 / 180.0),
      _height / 2,
      centerZ + r * sin (_pStatus->sun_degree () * 3.14 / 180.0),
      1.0f};
//   GLfloat lightPos0[] = {0.0f, 0.0f, -20.0f, 1.0f};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);

  // Draw terrain
   _pTerrainModel->draw ();

   // Draw objects on the field
  for (list< Ptr< Object > >::iterator it = _pObjects->begin ();
       it != _pObjects->end (); ++it)
  {
    _draw_obj ((*_pModels)[(*it)->type_id ()], *it);
	if( it == _pObjects->end() ) break;
  }

  glPopMatrix ();
}

void Scene::_draw_obj (Model& model, Ptr< Object > object)
{

  glPushMatrix ();
  glPushAttrib (GL_ENABLE_BIT);
  glPushAttrib (GL_CURRENT_BIT);

  // Transform
  glTranslatef (object->center ()[0], object->center ()[1],
    //18.0f);
    object->center ()[2]);

  glPushMatrix ();
  glRotatef (object->rotation ()[0], 1, 0, 0);
  glRotatef (object->rotation ()[1], 0, 1, 0);
  glRotatef (object->rotation ()[2], 0, 0, 1);

  /***********************yayang*******************/
  //object->update ();
  model.draw (object);


  // Draw object status (Selected, Under Attack, etc)
  glPushMatrix ();

  float objRadius = object->properties ()->radius ();

  // NOT DONE HERE <--------------------------------------

  glPopMatrix ();

  glPopMatrix ();

  // Draw object's amount number
  //glTranslatef (0.0f, -objRadius, 1.0f);
  /*ostringstream sout;
  sout << object->number_left ();
  string strNum = sout.str ();
  _pStringPainter->DrawString (strNum.c_str (), 2.0f);*/
  glBegin(GL_QUADS);
  glVertex3f(0,3,0.5);
  glVertex3f(0,3.5,0.5);
  glVertex3f(object->number_left (),3.5,0.5);
  glVertex3f(object->number_left (),3,0.5);
  glEnd();

  glPopAttrib ();
  glPopAttrib ();
  glPopMatrix ();

}